from sqlalchemy import Boolean, Column, DateTime, Integer, String, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.db.database import Base

class User(Base):
    """用户模型"""
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True)
    email = Column(String(100), unique=True, index=True)
    hashed_password = Column(String(100))
    full_name = Column(String(100))
    avatar = Column(String(255))
    bio = Column(Text)
    status = Column(String(20), default="active")  # 用户状态：active, disabled, banned
    is_active = Column(Boolean, default=True)
    is_verified = Column(Boolean, default=False)
    is_admin = Column(Boolean, default=False)  # 是否是管理员
    role = Column(String(20), default="user")  # 用户角色：user, merchant, admin
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    # 关系 - 使用字符串引用避免循环导入
    posts = relationship("Post", back_populates="author")
    followed_campsites = relationship("CampsiteFollow", back_populates="user")
    followed_users = relationship(
        "UserFollow",
        foreign_keys="UserFollow.follower_id",
        back_populates="follower"
    )
    followers = relationship(
        "UserFollow",
        foreign_keys="UserFollow.followed_id",
        back_populates="followed"
    )
    liked_posts = relationship("PostLike", back_populates="user")
    
    # 商家关联
    merchant = relationship("Merchant", back_populates="user", uselist=False)


class UserFollow(Base):
    """用户关注关系模型"""
    __tablename__ = "user_follows"

    id = Column(Integer, primary_key=True, index=True)
    follower_id = Column(Integer, ForeignKey("users.id"))
    followed_id = Column(Integer, ForeignKey("users.id"))
    created_at = Column(DateTime(timezone=True), server_default=func.now())

    # 关系
    follower = relationship("User", foreign_keys=[follower_id], back_populates="followed_users")
    followed = relationship("User", foreign_keys=[followed_id], back_populates="followers") 